import Axios from './core/Axios'
import { AxiosRequestConfig, AxiosStatic } from './types'
import { extend } from './helpers/util'
import defaultConfig from './default'
import mergeConfig from './core/mergeConfig'
import Cancel, { isCancel } from './cancel/Cancel'
import CancelToken from './cancel/CancelToken'

function createInstance(config: AxiosRequestConfig): AxiosStatic {
  const context = new Axios(config)
  let instance = Axios.prototype.request.bind(context)
  // instance 等于一个函数体，可以当做函数直接调用，context是一个实例对象
  extend(context, instance)
  // 这样做的原因 ==> 函数重载(axios(config), axios.get(config),即作为函数，也作为对象)
  return instance as AxiosStatic
}

const axios = createInstance(defaultConfig)
axios.create = function (config) {
  return createInstance(mergeConfig(defaultConfig, config))
}
axios.CancelToken = CancelToken
axios.Cancel = Cancel
axios.isCancel = isCancel

axios.all = function (promises) {
  return Promise.all(promises)
}

axios.spread = function (callback) {
  return function (resArr) {
    return callback.apply(null, resArr)
  }
}

axios.Axios = Axios

export default axios
